﻿using System.Data;
using System.Xml.Schema;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using AssetManageSystem.Model.AssetManage;
using AssetManageSystem.ViewModel.AssetManage.AssetInfoVMs;
using AssetManageSystem.Model;
using AssetManageSystem.Model.Enum;


namespace AssetManageSystem.ViewModel.AssetManage.AssetScrapVMs
{
    public partial class AssetScrapVM : BaseCRUDVM<AssetScrap>
    {
        public List<ComboSelectListItem> AllAssetIds { get; set; }
        [Display(Name = "资产选择")]
        public List<string> SelectedAssetIdIDs { get; set; }

        public AssetInfoListVM AssetInfoList { get; set; }

        //public AssetInfoCzListVM AssetInfoCzList { get; set; }

        public AssetScrapVM()
        {
            SetInclude(x => x.AssetId);
            SetInclude(x => x.AssetInfos);
        }

        protected override void InitVM()
        {
            AssetInfoList = Wtm.CreateVM<AssetInfoListVM>();

            AllAssetIds = DC.Set<AssetInfo>().GetSelectListItems(Wtm, y => y.AsName);
            SelectedAssetIdIDs = Entity.AssetId?.Select(x => x.AssetId.ToString()).ToList();
            Entity.DocNumber = "BF" + Helper.RandomNumber.GetRandom();
        }

        public override void DoAdd()
        {
            Entity.AssetId = new List<AssetScrapMiddleTable>();

            if (SelectedAssetIdIDs != null)
            {
                foreach (var id in SelectedAssetIdIDs)
                {
                    AssetScrapMiddleTable middle = new AssetScrapMiddleTable();
                    middle.SetPropertyValue("AssetId", id);
                    Entity.AssetId.Add(middle);
                }
            }

            //修改资产list的status的值为报废
            foreach (var sid in SelectedAssetIdIDs)
            {
                if (sid != null)
                {
                    var info = DC.Set<AssetInfo>().Where(x => x.ID.ToString() == sid).Select(x => x).ToList().FirstOrDefault();
                    info.Status = AsStatusEnum.Scrap;
                    DC.SaveChanges();
                }
            }

            base.DoAdd();
        }

        public override void DoEdit(bool updateAllFields = false)
        {
            Entity.AssetId = new List<AssetScrapMiddleTable>();
            if (SelectedAssetIdIDs != null)
            {
                foreach (var item in SelectedAssetIdIDs)
                {
                    AssetScrapMiddleTable middle = new AssetScrapMiddleTable();
                    middle.SetPropertyValue("AssetId", item);
                    Entity.AssetId.Add(middle);
                }
            }

            base.DoEdit(updateAllFields);
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}
